import axios from 'axios'
import { Message, Loading } from 'element-ui'
import router from '@/router'
import store from '@/store'
import { getToken } from '@/utils/auth'

let loadingInstance
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 15000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    const { showLoading = false } = config
    if (showLoading) {
      loadingInstance = Loading.service({
        // lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 0)'
      })
    }
    const token = getToken()
    if (token) {
      config.headers['Authentication'] = token
    }
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    const { showError = true, showLoading = false } = response.config
    showLoading && loadingInstance?.close()
    const { data, code } = res || {}
    if (code === 200) {
      return data || {}
    } else if (code === 401) {
      store.dispatch('user/logout')
      // 跳转登录
      router.push({
        path: '/login'
      })
      return false
    } else {
      if (showError) {
        Message({
          message: res.msg || 'Error',
          type: 'error'
        })
      }
      return Promise.reject(res.data)
    }
  },
  error => {
    const { config = {}, response = {}} = error
    const { showError = true, showLoading = false } = config
    if (response.status === 401) {
      store.dispatch('user/logout')
      router.push({
        path: '/login'
      })
      return false
    }
    if (showError) {
      Message({
        message: error.message || '服务繁忙，请稍后再试',
        type: 'error'
      })
    }
    showLoading && loadingInstance?.close()
    return Promise.reject(error)
  }
)

export default service
